get.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { z } from 'zod';
  3. import { RoleService } from '@/server/modules/roles/role.service';
  4. import { AppDataSource } from '@/server/data-source';
  5. import { ErrorSchema } from '@/server/utils/errorHandler';
  6. import { RoleSchema } from '@/server/modules/roles/role.entity';
  7. import { authMiddleware } from '@/server/middleware/auth';
  8. import { AuthContext } from '@/server/types/context';
  9. import { logger } from '@/server/utils/logger';
  10. // 路径参数Schema
  11. const GetParamsSchema = z.object({
  12. id: z.coerce.number().int().positive().openapi({
  13. param: { name: 'id', in: 'path' },
  14. example: 1,
  15. description: '角色ID'
  16. })
  17. });
  18. // 路由定义
  19. const routeDef = createRoute({
  20. method: 'get',
  21. path: '/{id}',
  22. middleware: [authMiddleware],
  23. request: {
  24. params: GetParamsSchema
  25. },
  26. responses: {
  27. 200: {
  28. description: '获取角色详情成功',
  29. content: {
  30. 'application/json': {
  31. schema: z.object({
  32. code: z.number().openapi({ example: 200 }),
  33. message: z.string().openapi({ example: '获取角色详情成功' }),
  34. data: RoleSchema
  35. })
  36. }
  37. }
  38. },
  39. 400: {
  40. description: '请求参数错误',
  41. content: {
  42. 'application/json': { schema: ErrorSchema }
  43. }
  44. },
  45. 404: {
  46. description: '角色不存在',
  47. content: {
  48. 'application/json': { schema: ErrorSchema }
  49. }
  50. },
  51. 500: {
  52. description: '服务器内部错误',
  53. content: {
  54. 'application/json': { schema: ErrorSchema }
  55. }
  56. }
  57. },
  58. tags: ['角色管理']
  59. });
  60. // 创建路由实例
  61. const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  62. try {
  63. const roleService = new RoleService(AppDataSource);
  64. const { id } = c.req.valid('param');
  65. const role = await roleService.findById(id);
  66. logger.api(`获取角色详情成功,ID: ${id}`);
  67. return c.json({
  68. code: 200,
  69. message: '获取角色详情成功',
  70. data: role
  71. }, 200);
  72. } catch (error) {
  73. const message = error instanceof Error ? error.message : '获取角色详情失败';
  74. const status = message.includes('不存在') ? 404 : 500;
  75. logger.error(`获取角色详情失败,ID: ${c.req.valid('param').id}, 错误: ${message}`);
  76. return c.json({
  77. code: status,
  78. message
  79. }, status);
  80. }
  81. });
  82. export default app;